package com.may.wind.service;

import com.may.wind.dao.PermissionRepository;
import com.may.wind.dao.RolePermissionRepository;
import com.may.wind.entity.Permission;
import com.may.wind.entity.Role;
import com.may.wind.entity.RolePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PermissionService {
    @Autowired
    PermissionRepository permissionRepository;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RoleService roleService;
    @Autowired
    RolePermissionService rolePermissionService;
    @Autowired
    RolePermissionRepository rolePermissionRepository;
    @Autowired
    UserService userService;

    public List<Permission> getAll() {
        return permissionRepository.findAll();
    }

    /**
     * Determine whether client requires permission when requests
     * a certain API.
     *
     * @param requestAPI API requested by client
     * @return true when requestAPI is found in the DB
     */
    public boolean needFilter(String requestAPI) {
        List<Permission> permissions = permissionRepository.findAll();
        for (Permission permission : permissions) {
            // match prefix
            if (requestAPI.startsWith(permission.getUrl())) {
                return true;
            }
        }
        return false;
    }

    public Set<Permission> getPermissionsByRoleId(long roleId) {
        List<Long> permissionIds = rolePermissionService.findAllByRoleId(roleId).stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
        return permissionRepository.findAllById(permissionIds).stream().collect(Collectors.toSet());
    }

    public Set<String> getPermissionUrlsByUser(String username) {
        List<Long> roleIds = roleService.getAllByUser(username).stream().map(Role::getId).collect(Collectors.toList());
        List<Long> permissionIds = rolePermissionRepository.findAllByRoleIdIn(roleIds).stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
        List<Permission> perms = permissionRepository.findAllById(permissionIds);
        Set<String> urls = perms.stream().map(Permission::getUrl).collect(Collectors.toSet());
        return urls;
    }
}
